﻿using System;
using System.Net;
using System.Web;
using System.IO;
using System.Text;
using DataModel;
using System.Collections.Generic;
using System.Windows.Forms;

[assembly:CLSCompliant(true)]
namespace DataExtraction
{
    public class DelViento
    {
        private Uri uri;
        private bool ready;

        public Uri Uri
        {
            get { return uri; }
            set { uri = value; }
        }

        private static DelViento instance;

        public static DelViento Instance
        {
            get { return DelViento.instance; }
        }

        static DelViento()
        {
            DelViento.instance = new DelViento();
            DelViento.instance.Uri = new Uri("http://www.windguru.com/es/index.php?sc=261");
        }

        private DelViento()
        {
        }

        public string PageAsString
        {
            get
            {
                WebRequest myWebRequest = WebRequest.Create(Uri);

                WebResponse myWebResponse = myWebRequest.GetResponse();

                Stream ReceiveStream = myWebResponse.GetResponseStream();

                Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

                StreamReader readStream = new StreamReader(ReceiveStream, encode);

                return readStream.ReadToEnd();
            }
        }

        public void LoadPage(WebBrowser webControl1)
        {
            //from http://bytes.com/forum/thread607769.html
            WebBrowser webControl = new WebBrowser();
            //string pageAsString = this.PageAsString;
            webControl.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webControl_DocumentCompleted);
            //webControl.DocumentText = pageAsString;
            webControl.Navigate(this.Uri);
            //while (webControl.ReadyState != WebBrowserReadyState.Loaded)
            //    System.Threading.Thread.Sleep(100);

            do
            {
                Application.DoEvents();
            } while (webControl.ReadyState != WebBrowserReadyState.Complete);

            HtmlDocument doc = webControl.Document;

            HtmlElementCollection tables = doc.GetElementsByTagName("table");
            string className = "inferior_contenedor_8horas";
            foreach (HtmlElement table in tables)
            {
                if (table.GetAttribute("class") == className)
                    Console.WriteLine("table found");
            }
        }

        void webControl_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            this.ready = true;
        }

        public IEnumerable<Wind> GetHistoricData()
        {
            throw new NotImplementedException();
        }
    }
}
